package com.xy.farm.activity.widget;

import android.content.Context;
import android.support.v4.view.NestedScrollingParent;
import android.support.v4.view.ViewCompat;
import android.util.AttributeSet;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.OverScroller;

/**
 * Created by 1174607250 on 2018/8/5.
 */

public class FarmLinearLayout extends LinearLayout implements NestedScrollingParent
{
    private View childView;
    private OverScroller mScroller;
    public FarmLinearLayout(Context context, AttributeSet attrs)
    {
        super(context, attrs);
    }
    @Override
    protected void onFinishInflate()
    {
        super.onFinishInflate();
        childView = getChildAt(0);
        mScroller = new OverScroller(getContext());
    }
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
    {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        for (int i = 0 ; i < getChildCount() ; i ++ )
        {
            measureChild(getChildAt(i),widthMeasureSpec,heightMeasureSpec);
        }
    }
    @Override
    public void scrollTo(int x, int y)
    {
        if (y < 0)
            y = 0;
        if (y > childView.getHeight())
            y = childView.getHeight();
        if (y != getScrollY())
            super.scrollTo(x, y);
    }
    @Override
    public void computeScroll()
    {
        if (mScroller.computeScrollOffset())
        {
            scrollTo(0, mScroller.getCurrY());
            invalidate();
        }
    }

    @Override
    public boolean onNestedPreFling(View target, float velocityX, float velocityY)
    {
        if (getScrollY() >= childView.getHeight())
            return false;
        mScroller.fling(0, getScrollY(), 0 , (int)velocityY, 0, 0, 0, childView.getHeight());
        invalidate();
        return true;
    }
    @Override
    public boolean onStartNestedScroll(View child, View target, int nestedScrollAxes)
    {
        return true;
    }
    @Override
    public void onNestedPreScroll(View target, int dx, int dy, int[] consumed)
    {
        boolean show = dy > 0 && getScrollY() < childView.getHeight();
        boolean hide = dy < 0 && getScrollY() >= 0 && !ViewCompat.canScrollVertically(target, -1);
        if (show || hide)
        {
            scrollBy(0, dy);
            consumed[1] = dy;
        }
    }
    @Override
    public int getNestedScrollAxes()
    {
        return 0;
    }
}
